import { defineStore } from 'pinia';

//控制任务数据
export const useTaskStore = defineStore('task', {
  state: () => ({
    tableData: [],
    upload_task_id:0
  }),
  getters:{},
  actions: {
    loadData() {
      // 模拟异步加载数据
      const sql = "SELECT * FROM task"
      window.send_main.query_db(sql, (result) => {
        // 处理查询结果
          this.tableData = result
      });
    }
  },
});

//控制页面显示数据
export const usePageShowStore = defineStore('pageShow',{
  state:() => ({
    active:"4" //0 默认页面 1-1 创建任务 1-2 创建任务导入数据 2 任务列表 3子任务列表  3-1子任务查看
  }),
  getters:{},
  actions:{
    changeMenu(index) {
        this.active = index
    }
  }
})
//控制任务详情页数据

export const useTaskDetailStore = defineStore('taskDetail',{
  state:() => ({
    active_task_id:"4", //控制当前任务ID
    tableData:[],
    detail:[],//当前页详情
    currentPage: 0, // 当前页码
    pageSize: 15, // 每页显示的条数
    total: 0, // 总数
  }),
  getters:{},
  actions:{
    loadData () {
      //先看总数
      const total_sql = `SELECT COUNT(id) AS a FROM sub_task WHERE p_id = ${this.detail.id}`
      console.log(total_sql)
      window.send_main.query_db(total_sql, (r) => {
        // 处理查询结果
        this.total = parseInt(r[0].a)
      })
      const sql = `SELECT * FROM sub_task WHERE p_id = ${this.detail.id} LIMIT ${this.pageSize} OFFSET ${this.currentPage * this.pageSize};`
      console.log(sql)
      window.send_main.query_db(sql, (result) => {
        console.log(result)
        // 处理查询结果
        this.tableData = result
      })
      },
    current_change(current) {
      current = current - 1
      this.currentPage = current
      this.loadData()
    }
  }

})

//子任务查看页面

export const useSubTaskStore = defineStore('subTask',{
  state:() => ({
    active_subtask_id:"0", //当前子任务id
    active_task_id:"0", //当前任务ID
    tableData:[],
    mindData:[],//导图数据
    detail:[],//当前页详情
    currentPage: 0, // 当前页码
    pageSize: 10, // 每页显示的条数
    total: 0, // 总数
    search:{
      j_y_k_h:"",//交易卡号
      j_y_h_m:"",//交易户名
      j_y_j_e:"",//交易金额
      j_y_s_j:{
        start:"",
        end:"",
      },//交易时间
      d_s_h_m:"",//对手户名
      j_y_d_s_z_h:"",//对手卡号

    },//搜索参数
    active_level:1,//追踪的当前层级
    level_option:[
    ],//层级选择
    selected_ids:new Set(),
    active_ids:[],//当前的ids
    basic_where:"",//基本where条件
    parent_j_y_d_s_z_h:new Set(),//上一层的交易对手账号，也就是这一层的基础条件
  }),
  getters:{},
  actions:{
    loadData () {
      let where = ""
      for (const [key, value] of Object.entries(this.search)) {
        if (value !== null && value !== undefined && value !== '') {
          if (key == "j_y_s_j" ) {
            if (value.start !== null && value.start !== undefined && value.start !== '') {
              where += ` AND j_y_s_j BETWEEN '${value.start}' AND '${value.end}'`
            }
          } else if (key == "j_y_j_e"){
            where += ` AND ${key} > ${value}`
          } else {
            where += ` AND ${key} LIKE '%${value}%'`
          }
        }
      }
      console.log(this.basic_where)
      console.log(where)
      where = this.basic_where+where
      const table_name = `transaction_table_${this.detail.p_id}`
      //先看总数
      const total_sql = `SELECT COUNT(id) AS a FROM ${table_name} WHERE 1=1${where}`
      console.log(total_sql)
      window.send_main.query_db(total_sql, (r) => {
        // 处理查询结果
        this.total = parseInt(r[0].a)
      })
      //下面的查询需要拼接where
      const sql = `SELECT * FROM ${table_name} WHERE 1=1${where} ORDER BY id DESC LIMIT ${this.pageSize} OFFSET ${this.currentPage * this.pageSize}`
      console.log(sql)
      window.send_main.query_db(sql, (result) => {
        console.log(result)
        // 处理查询结果
        this.tableData = result

        this.buildMindData()
      })
    },
    buildMindData (){
      console.log(this.tableData)


    },
    current_change(current) {
      this.currentPage = current - 1
      this.loadData()
    },
    buildWhere(state){
      //state 状态  分三种  =2 当前有层级，那么执行最后一层的查询条件，就是t_id IN 最后一层的所有id 都是添加基础where条件
      //state 状态  分三种  =3 从追踪过来的，添加基础where条件 （上一层的交易对手帐号，作为这一层的基础条件，后面可以自行添加where）
     if (state == 2) {
        let where = ` AND id IN (${this.active_ids.join(",")})`
        this.basic_where = where
      } else if (state == 3) {
        const array = Array.from(this.parent_j_y_d_s_z_h);
        const filteredArray = array.filter(value => value !== null && value !== "");
        const joinedString = filteredArray.map(item => `'${item}'`).join(",");
        console.log(joinedString)
        if (joinedString.length > 0) {
          this.basic_where = ` AND j_y_k_h IN (${joinedString})`;
        } else if (state == 1){
          // this.basic_where = ""; // 如果数组为空，将 where 设置为空字符串
        }
      }

    },
    clear(){
      this.active_level = 1
      this.level_option = []
      this.selected_ids = new Set()
      this.active_ids = []
      this.basic_where = ""
    },
    init () {
      //先清空各种数据
      this.clear()
      this.search.j_y_s_j.start = ""
      this.search.j_y_s_j.end = ""
      const sql = `SELECT * FROM track WHERE sub_task_id = ${this.detail.id} ORDER BY level DESC LIMIT 1`
      window.send_main.query_db(sql, (result) => {
        if (result.length > 0) {
          //最上一条数据的level为总的追踪层级,通过该数量来确定this.active_level和this.level_options
          this.active_level = parseInt(result[0].level)
          console.log(this.active_level)
          for (let i = 1; i <= this.active_level; i++) {
            this.level_option.push({value: i, label: i + "级"})
          }
          const sql = `SELECT * FROM track WHERE sub_task_id AND level = ${this.active_level}`
          window.send_main.query_db(sql, (result) => {
            this.active_ids = result.map(item => item.transaction_table_id);
            result.forEach(item => {
              this.selected_ids.add(item.transaction_table_id);
            });
            this.buildWhere(2) //要获取当前层级的ID来构造where
            console.log(this.selected_ids)
            this.loadData()
          })
        } else {
          //最初状态进入，一次没保存过
          //清空各种数据
          this.loadData()
        }
        //然后再获取当前的查询条件
      })
    },
    async track_init () {
      //追踪初始化
      //先清空
      this.level_option = []
      this.selected_ids = new Set()
      this.active_ids = []
      this.basic_where = ""

      this.clearWhere()
      const c_sql = `SELECT * FROM track WHERE sub_task_id = ${this.detail.id} ORDER BY level DESC LIMIT 1`
      //最上一条数据的level为总的追踪层级,通过该数量来确定this.active_level和this.level_options
      window.send_main.query_db(c_sql, (result) => {
        if (result.length > 0) {
          //最上一条数据的level为总的追踪层级,通过该数量来确定this.active_level和this.level_options
          this.active_level = parseInt(result[0].level) + 1
          for (let i = 1; i <= this.active_level; i++) {
            this.level_option.push({value: i, label: i + "级"})
          }
          const sql = `SELECT * FROM track WHERE sub_task_id AND level = ${this.active_level}`
          window.send_main.query_db(sql, (result) => {
            this.active_ids = result.map(item => item.transaction_table_id);
            result.forEach(item => {
              this.selected_ids.add(item.transaction_table_id);
            });
            this.buildWhere(2) //要获取当前层级的ID来构造where
            console.log(this.selected_ids)
            this.loadData()

          })
        }
      })

      //查询出当前的
      const sql = `SELECT * FROM track WHERE sub_task_id = ${this.detail.id} ORDER BY level DESC LIMIT 1`
      window.send_main.query_db(sql, (result) => {
        const select_sql = `SELECT * FROM transaction_table_${this.detail.p_id} WHERE id IN (SELECT transaction_table_id FROM track WHERE sub_task_id = ${this.detail.id} AND level=${result[0].level}) ORDER BY j_y_s_j ASC `
        window.send_main.query_db(select_sql,(res) => {
          res.forEach((row, index) => {
            // 判断是否为第一个元素
            if (index === 0) {
              // 这是第一个元素
              const originalDate = new Date(row.j_y_s_j);
              //最早时间往前加5天
              const newDateForward = new Date(originalDate.getTime() - 5 * 24 * 60 * 60 * 1000);
              this.search.j_y_s_j.start = this.formatDate(newDateForward)
            }

            // 判断是否为最后一个元素
            if (index === res.length - 1) {
              // 这是最后一个元素
              const originalDate = new Date(row.j_y_s_j);
              //最晚时间往后加30天
              const newDateBackward = new Date(originalDate.getTime() + 30 * 24 * 60 * 60 * 1000);
              this.search.j_y_s_j.end = this.formatDate(newDateBackward)
            }
            // 其他操作
            this.parent_j_y_d_s_z_h.add(row.j_y_d_s_z_h);
          });
          //拼接基础where条件
          this.buildWhere(2)
          //加载数据
          this.loadData()
        })
      })
    },

    formatDate(date) {
      //格式化时间
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    clearWhere(){
      //清空搜索条件方法
      this.search.j_y_k_h = ''
      this.search.j_y_z_h = ''
      this.search.j_y_j_e = ''
      this.search.j_y_s_j.start = ''
      this.search.j_y_s_j.end = ''
      this.search.d_s_h_m = ''
      this.search.j_y_d_s_z_h = ''
    },
    handleChange(value){
      //切换层级

      this.active_ids = []
      this.basic_where = ""

      //查询出当前的
      const select_sql = `SELECT * FROM transaction_table_${this.detail.p_id} WHERE id IN (SELECT transaction_table_id FROM track WHERE sub_task_id = ${this.detail.id} AND level=${value}) ORDER BY j_y_s_j ASC `
      window.send_main.query_db(select_sql,(res) => {
        res.forEach((row) => {
          // 其他操作
          this.active_ids.push(row.id);
        });
        //拼接基础where条件
        this.buildWhere(2)
        console.log(this.basic_where)
        //加载数据
        this.loadData()
      })
    }
  }
})

//查看走向
export const useTrendStore = defineStore('trend',{

  state:() => ({
    tableData:[],
  }),
  getters:{},
  actions: {
    loadData(row) {
      console.log(row)
      const sql = `SELECT track.*, transaction_table_${row.p_id}.*
FROM track
LEFT JOIN transaction_table_${row.p_id} ON track.transaction_table_id = transaction_table_${row.p_id}.id
WHERE track.sub_task_id = ${row.id}
ORDER BY track.level ASC;`
      console.log(sql)
      window.send_main.query_db(sql, (result) => {
        // 处理查询结果
        this.tableData = result
      })
    },
  },

})
